#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>

#define User 1
#define Creater 2
#define Default -1
#define Read O_RDONLY
#define Write O_WRONLY
#define SIZE 4096

const std::string comm_path = "./myfifo"; // 通信文件的路径

class NamedPipe
{
private:
    bool OpenNamePipe(int mode) // 打开文件
    {
        _fd = open(_path_name.c_str(), mode);
        if (_fd < 0)
        {
            return false;
        }

        return true;
    }

public:
    NamedPipe(const std::string &path, int who) // 构造
        : _path_name(path), _id(who), _fd(Default)
    {
        if (who == Creater)
        {
            int n = mkfifo(path.c_str(), 0666);
            if (n != 0)
            {
                perror("mkfifo");
                exit(-1);
            }

            std::cout << "creater namedpipe success" << std::endl;
        }
    }

    ~NamedPipe() // 析构
    {
        if (_id == Creater)
        {
            int res = unlink(_path_name.c_str());
            if (res != 0)
            {
                perror("unlink");
            }

            std::cout << "creater free named pipe" << std::endl;
        }

        if (_fd != Default)
            close(_fd);
    }

    bool OPenForRead() // 以读的方式打开
    {
        return OpenNamePipe(Read);
    }

    bool OPenForWrite() // 以写的方式打开
    {
        return OpenNamePipe(Write);
    }

    int ReadNamePipe(std::string *out) // 读管道
    {
        char buffer[SIZE];
        int n = read(_fd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    int WriteNamePipe(const std::string &in) // 写管道
    {
        return write(_fd, in.c_str(), in.size());
    }

private:
    std::string _path_name; // 管道文件的路径
    int _id;                // 操作者
    int _fd;                // 文件描述符
};